package org.zjvis.datascience.common.util.db;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringUtils;
import org.zjvis.datascience.common.constant.DatabaseConstant;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

/**
 * @description : MD5 SHA 加密工具类
 * @date 2021-10-15
 */
public class CryptoUtil {
    public final static String HMAC_MD5 = "HmacMD5";
    public final static String HMAC_SHA1 = "HmacSHA1";

    /**
     * hmac加密
     *
     * @param src
     * @param key
     * @param type
     * @return
     * @throws Exception
     */
    public static String hmac(String src, String key, String type) throws Exception {
        //密钥
        SecretKey secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), type);
        //实例化mac
        Mac mac = Mac.getInstance(secretKey.getAlgorithm());
        //初始化mac
        mac.init(secretKey);
        return Hex.encodeHexString(mac.doFinal(src.getBytes(StandardCharsets.UTF_8)));
    }

    /**
     * hmacMD5加密
     *
     * @param src
     * @param key
     * @return
     * @throws Exception
     */
    public static String hmacMD5(String src, String key) throws Exception {
        return hmac(src, key, HMAC_MD5);
    }

    /**
     * hmacMD5加密（使用默认密钥）
     *
     * @param src
     * @return
     * @throws Exception
     */
    public static String hmacMD5(String src) throws Exception {
        return hmacMD5(src, DatabaseConstant.SECRET_KEY);
    }

    /**
     * hmacSHA1加密
     *
     * @param src
     * @param key
     * @return
     * @throws Exception
     */
    public static String hmacSHA1(String src, String key) throws Exception {
        return hmac(src, key, HMAC_SHA1);
    }

    /**
     * hmacSHA1加密（使用默认密钥）
     *
     * @param src
     * @return
     * @throws Exception
     */
    public static String hmacSHA1(String src) throws Exception {
        return hmacSHA1(src, DatabaseConstant.SECRET_KEY);
    }

    /**
     * 字符串打码（处理逻辑要和DatabaseConstant.MOSAIC_SQL一致）
     *
     * @param src
     * @return
     */
    public static String stringMosaic(String src) {
        if (StringUtils.isBlank(src)) {
            return "";
        }
        //处理逻辑要和DatabaseConstant.MOSAIC_SQL一致
        if (src.length() < 6) {
            return "****";
        } else if (src.length() > 10) {
            return src.substring(0, 3) + "****" + src.substring(src.length() - 4, src.length());
        } else {
            return src.substring(0, (src.length() - 4) / 2) + "****" + src.substring((src.length() - 4) / 2 + 4, src.length());
        }
    }

}
